<!--
 * @Description:
 * @Author: william
 * @Date: 2025-02-17 16:47:40
 * @LastEditors: william
 * @LastEditTime: 2025-09-12 10:22:55
-->
<template>
  <BaseDialog
    v-model="dialogVisible"
    :title="title"
    width="1100px"
    :before-close="handleClose"
  >
    <el-form
      ref="refDialogForm"
      v-loading="formLoading"
      class="set-dialog-form"
      :label-width="
        language === 'en' ? '180px' : type == 'add' ? '80px' : '110px'
      "
      :model="formData"
      :rules="rules"
    >
      <el-row>
        <el-col v-if="type == 'add'" :span="24">
          <el-form-item :label="$t('fleet.customerName')" prop="customerId">
            <div class="customerWrap">
              <SelectCustomer
                :key="customerKey"
                v-model="formData.customerId"
                :label="$t('fleet.customerName')"
              />
              <div class="add-customer">
                <el-button text type="primary" @click="handleAddCustomer">{{
                  $t('public.add')
                }}</el-button>
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col v-if="type == 'edit'" :span="12">
          <el-form-item :label="$t('fleet.customerName')">
            <TextInput
              v-model="formData.customerName"
              :placeholder="$t('fleet.customerName')"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col v-if="type === 'edit'" :span="12">
          <el-form-item
            :label="$t('fleet.customerContact')"
            prop="customerContact"
          >
            <TextInput
              v-model="formData.customerContact"
              :label="$t('fleet.customerContact')"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="type === 'edit'" :span="12">
          <el-form-item
            :label="$t('fleet.contactPhone')"
            prop="customerContactPhone"
          >
            <InputPhone
              v-model="formData.customerContactPhone"
              :label="$t('fleet.contactPhone')"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="type === 'edit'" :span="12">
          <el-form-item
            :label="$t('fleet.customerEmail')"
            prop="customerContactEmail"
          >
            <TextInput
              v-model="formData.customerContactEmail"
              :label="$t('fleet.customerEmail')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            :label="$t('fleet.addTrip')"
            style="margin-bottom: 0"
            required
          >
            <template #label>
              <label>{{ $t('fleet.addTrip') }}</label>
            </template>
            <el-button
              type="primary"
              style="margin-bottom: 10px"
              @click="handleAddTravel"
              >{{ $t('public.add') }}</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label-width="0" class="form-item-table" prop="tripInfo">
            <BaseTable
              ref="refTravelTable"
              v-loading="tableLoading"
              :data="formData.tripInfo"
              row-key="id"
            >
              <TableColumn :label="$t('fleet.departure')" class="ignore">
                <TableColumn
                  prop="startRegionCode"
                  :label="$t('public.region')"
                  :column-width="travelColumnWidth.startRegionCode"
                >
                  <template #default="{ row }">
                    <span>{{
                      g_utils.getRegionName(row.startRegionCode)
                    }}</span>
                  </template>
                </TableColumn>
                <TableColumn
                  prop="startAddress"
                  :label="$t('public.detailAddress')"
                  :column-width="travelColumnWidth.startAddress"
                />
              </TableColumn>
              <TableColumn :label="$t('fleet.destination')" class="ignore">
                <TableColumn
                  prop="endRegionCode"
                  :label="$t('public.region')"
                  :column-width="travelColumnWidth.endRegionCode"
                >
                  <template #default="{ row }">
                    <span>{{ g_utils.getRegionName(row.endRegionCode) }}</span>
                  </template>
                </TableColumn>
                <TableColumn
                  prop="endAddress"
                  :label="$t('public.detailAddress')"
                  :column-width="travelColumnWidth.endAddress"
                />
              </TableColumn>
              <TableColumn
                prop="startTime"
                :label="$t('fleet.departureTime')"
                :column-width="travelColumnWidth.startTime"
              />
              <TableColumn
                prop="endTime"
                :label="$t('public.endTime')"
                :column-width="travelColumnWidth.endTime"
              />
              <TableColumn
                prop="through"
                :label="$t('fleet.passingScenery')"
                :column-width="travelColumnWidth.through"
              />
              <TableColumn
                prop="kilometres"
                :label="$t('fleet.travelDistance')"
                :column-width="travelColumnWidth.kilometres"
              >
                <template #default="{ row }"
                  >{{ row.kilometres }}{{ $t('fleet.kilometer') }}</template
                >
              </TableColumn>
              <TableColumn
                prop="action"
                fixed="right"
                :label="$t('public.action')"
                :column-width="travelColumnWidth.action"
              >
                <template #default="{ row, $index }">
                  <el-button text @click="handleTravelEdit(row, $index)">
                    {{ $t('public.edit') }}
                  </el-button>
                  <el-button text @click="handleTravelDelete(row, $index)">{{
                    $t('public.delete')
                  }}</el-button>
                </template>
              </TableColumn>
            </BaseTable>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('fleet.travelerCount')" prop="peopleCount">
            <TextInput
              v-model="formData.peopleCount"
              :label="$t('fleet.travelerCount')"
              verify-type="nzint"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('fleet.travelDays')" prop="days">
            <TextInput
              v-model="formData.days"
              :label="$t('fleet.travelDays')"
              verify-type="nzint"
            >
              <template #suffix>{{ $t('public.sky') }}</template>
            </TextInput>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item :label="$t('fleet.roundTrip')" prop="isReturn">
            <el-radio-group v-model="formData.isReturn">
              <el-radio
                v-for="item in g_options.roundTripOptions"
                :key="item.value"
                :value="item.value"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col> -->
        <el-col v-if="type === 'edit'" :span="24">
          <el-form-item
            :label="$t('fleet.allocateVehicle')"
            style="margin-bottom: 0"
          >
            <template #label>
              <label>{{ $t('fleet.allocateVehicle') }}</label>
            </template>
            <el-button
              type="primary"
              style="margin-bottom: 10px"
              @click="handleAddVehicle"
              >{{ $t('fleet.manualAssign') }}</el-button
            >
            <el-button
              type="primary"
              style="margin-bottom: 10px"
              @click="handleAutoAssign"
              >{{ $t('fleet.autoAssign') }}</el-button
            >
          </el-form-item>
        </el-col>
        <el-col v-if="type === 'edit'" :span="24">
          <el-form-item label-width="0" prop="vehicles" class="form-item-table">
            <BaseTable
              ref="refContentTable"
              v-loading="tableLoading"
              :data="formData.vehicles"
              row-key="id"
            >
              <TableColumn
                prop="vehicleNumber"
                :label="$t('fleet.vehicleNumber')"
                :column-width="columnWidthObj.vehicleNumber"
              >
                <template #default="{ $index }">
                  <span>{{ $t('fleet.vehicle') }}{{ $index + 1 }}</span>
                </template>
              </TableColumn>
              <TableColumn
                prop="vehiclePlate"
                :label="$t('fleet.licensePlate')"
                :column-width="columnWidthObj.vehiclePlate"
              />
              <TableColumn
                prop="seatCount"
                :label="$t('fleet.loadCapacity')"
                :column-width="columnWidthObj.seatCount"
              />
              <TableColumn
                prop="status"
                :label="$t('fleet.vehicleStatus')"
                :column-width="columnWidthObj.status"
              >
                <template #default="{ row }">
                  <span
                    class="dot-status"
                    :class="
                      g_options.getOptionText(
                        g_options.vehicleStatusOptions,
                        row.status,
                        '--',
                        'class'
                      )
                    "
                    >{{
                      g_options.getOptionText(
                        g_options.vehicleStatusOptions,
                        row.status,
                        '--'
                      )
                    }}</span
                  >
                </template>
              </TableColumn>
              <TableColumn
                prop="regionCode"
                :label="$t('fleet.region')"
                :column-width="columnWidthObj.regionCode"
              >
                <template #default="{ row }">
                  <span>{{ g_utils.getRegionName(row.regionCode) }}</span>
                </template>
              </TableColumn>
              <TableColumn
                prop="action"
                fixed="right"
                :label="$t('public.action')"
                :column-width="columnWidthObj.action"
              >
                <template #default="{ row, $index }">
                  <el-button text @click="handleViewSchedule(row)">
                    {{ $t('fleet.schedule') }}
                  </el-button>
                  <el-button text @click="handleVehicleDetail(row)">
                    {{ $t('public.detail') }}
                  </el-button>
                  <!-- <el-button text @click="handleVehicleChange($index)">
                    {{ $t('fleet.change') }}
                  </el-button> -->
                  <el-button text @click="handleVehicleDelete(row, $index)">{{
                    $t('public.delete')
                  }}</el-button>
                </template>
              </TableColumn>
            </BaseTable>
          </el-form-item>
        </el-col>
        <el-col v-if="type === 'add'" :span="12">
          <el-form-item :label="$t('fleet.billType')" prop="vehicleBillType">
            <el-select
              v-model="formData.vehicleBillType"
              :placeholder="
                g_rules.zhAndEnShowMsg(
                  g_t('public.pleaseSelect'),
                  $t('fleet.billType')
                )
              "
            >
              <el-option
                v-for="item in g_options.vehicleBillingMethodOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('fleet.payType')" prop="payType">
            <el-radio-group v-model="formData.payType">
              <el-radio
                v-for="item in g_options.orderPayMethodOptions"
                :key="item.value"
                :value="item.value"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="type === 'add'" :span="12">
          <el-form-item :label="$t('fleet.quotePrice')" prop="customerBudget">
            <TextInput
              v-model="formData.customerBudget"
              :label="$t('fleet.quotePrice')"
              verify-type="float"
              @blur="handleInputBlur('customerBudget')"
            >
              <template #suffix>{{ $t('fleet.yuan') }}</template>
            </TextInput>
          </el-form-item>
        </el-col>
        <!-- <el-col v-if="type === 'add'" :span="12">
          <el-form-item :label="$t('fleet.costExpense')" prop="costExpense">
            <TextInput
              v-model="formData.costExpense"
              :label="$t('fleet.costExpense')"
              verifyType="float"
              @blur="handleInputBlur('costExpense')"
            >
              <template #suffix>{{ $t('fleet.yuan') }}</template>
            </TextInput>
          </el-form-item>
        </el-col> -->
        <!-- <el-col v-if="type === 'add'" :span="12">
          <el-form-item :label="$t('fleet.orderProfit')" prop="orderProfit">
            <TextInput
              v-model="formData.orderProfit"
              :label="$t('fleet.orderProfit')"
              verify-type="float"
              @blur="handleInputBlur('orderProfit')"
            >
              <template #suffix>{{ $t('fleet.yuan') }}</template>
            </TextInput>
          </el-form-item>
        </el-col> -->
        <el-col v-if="type === 'edit'" :span="12">
          <el-form-item
            :label="$t('fleet.emergencyContact')"
            prop="customerEmergencyContact"
          >
            <TextInput
              v-model="formData.customerEmergencyContact"
              :label="$t('fleet.emergencyContact')"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="type === 'edit'" :span="12">
          <el-form-item
            :label="$t('fleet.emergencyContactPhone')"
            prop="customerEmergencyContactPhone"
          >
            <InputPhone
              v-model="formData.customerEmergencyContactPhone"
              :label="$t('fleet.emergencyContactPhone')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('public.remark')" prop="remark">
            <TextInput
              v-model="formData.remark"
              type="textarea"
              :rows="2"
              :label="$t('public.remark')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('fleet.bookingSummary')" prop="note">
            <TextInput
              v-model="formData.note"
              type="textarea"
              :rows="2"
              :label="$t('fleet.bookingSummary')"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col v-if="type === 'add'" :span="24">
          <el-form-item prop="orderTextInfo">
            <TextInput
              v-model="formData.orderTextInfo"
              type="textarea"
              :maxlength="512"
              :rows="4"
              :placeholder="$t('fleet.orderTextInfo')"
            />
            <div class="paste-identify">
              <el-button type="primary" @click="handlePasteRecognize">{{
                $t('fleet.pasteAndRecognize')
              }}</el-button>
            </div>
          </el-form-item>
        </el-col> -->
      </el-row>
    </el-form>
    <AiParserInput
      v-if="type === 'add'"
      v-model="orderTextInfo"
      :loading="aiParserLoading"
      :placeholder="$t('fleet.orderTextInfo')"
      @aiClick="handlePasteRecognize"
    />
    <template #footer>
      <div class="form-dialog-footer">
        <!-- <el-button
          v-if="type === 'add'"
          type="primary"
          @click="handlePasteRecognize"
          >{{ $t('fleet.pasteAndRecognize') }}</el-button
        > -->
        <el-button plain @click="handleClose">{{
          $t('public.cancel')
        }}</el-button>
        <el-button type="primary" @click="handleSubmitForm">{{
          $t('public.confirm')
        }}</el-button>
      </div>
    </template>
  </BaseDialog>
  <AddCustomer
    v-if="addCustomerVisible"
    v-model="addCustomerVisible"
    @update="customerKey++"
  />
  <AddTravel2
    v-if="addTravelVisible"
    v-model="addTravelVisible"
    :row="travelRow"
    :type="travelType"
    @add="handleAddTravelCb"
    @update="handleUpdateTravelCb"
  />
  <SelectVehicle
    v-if="selectVehicleVisible"
    v-model="selectVehicleVisible"
    :vehicle-table-type="vehicleTableType"
    :tenant-id="formData.customerId"
    :vehicle-ids="selectVehicleIds"
    :vehicleStartTime="vehicleStartTime"
    :vehicleEndTime="vehicleEndTime"
    @select="handleSelectVehicle"
  />
  <!-- 日程 -->
  <Schedule
    v-if="scheduleVisible"
    v-model="scheduleVisible"
    :vehicle-id="rowId"
    type="view"
  />
  <DetailDialog v-if="detailVisible" :id="rowId" v-model="detailVisible" />
</template>

<script setup>
import AddTravel2 from './AddTravel.vue'
import AddCustomer from '@/views/customer/component/AddOrEditDialog.vue'
import SelectVehicle from './SelectVehicle'
import Schedule from '@/views/fleet/vehicle/component/Schedule.vue'
import DetailDialog from '@/views/fleet/vehicle/component/DetailDialog.vue'

const props = defineProps({
  type: {
    type: String,
    default: 'add' // add | edit
  },
  id: {
    type: String,
    default: ''
  },
  tenantId: {
    type: String,
    default: ''
  },
  row: {
    type: Object,
    default: () => {}
  }
})

const emit = defineEmits(['update'])
const dialogVisible = defineModel({
  type: Boolean,
  default: false
})
const { language } = storeToRefs(useAppStore())
const title = computed(() =>
  props.type === 'add' ? g_t('fleet.createOrder') : g_t('fleet.editOrder')
)

const refDialogForm = ref(null)
const formLoading = ref(false)
const formData = ref({
  // tenantId: props.tenantId,
  customerId: '',
  // customerName: '',
  // customerContact: '',
  // customerContactPhone: '',
  // customerContactEmail: '',
  tripInfo: [],
  peopleCount: '',
  days: '',
  vehicleBillType: '',
  payType: '',
  customerBudget: '',
  orderProfit: '',
  // isReturn: '',
  // vehicles: [],
  // costExpense: '',
  // customerEmergencyContact: '',
  // customerEmergencyContactPhone: '',
  remark: '',
  note: ''
})
const rules = {
  customerId: g_rules.selectRule(g_t('fleet.customerName')),
  customerContact: g_rules.commonInputText(g_t('fleet.customerContact')),
  customerContactPhone: g_rules.phone({
    label: g_t('fleet.contactPhone')
  }),
  customerContactEmail: g_rules.email({
    label: g_t('fleet.customerEmail'),
    required: false
  }),
  tripInfo: g_rules.selectRule(g_t('fleet.trip')),
  peopleCount: g_rules.travelerCount,
  days: g_rules.travelDays,
  // vehicleBillType: g_rules.selectRule(g_t('fleet.billType')),
  payType: g_rules.selectRule(g_t('fleet.payType')),
  customerBudget: g_rules.customerBudget,
  // orderProfit: g_rules.orderProfit,
  // isReturn: g_rules.selectRule(g_t('fleet.roundTrip')),
  // vehicles: g_rules.selectRule(g_t('fleet.vehicle')),
  // costExpense: g_rules.costExpense,
  // customerEmergencyContact: g_rules.commonInputText(
  //   g_t('fleet.emergencyContact')
  // ),
  customerEmergencyContactPhone: g_rules.phone({
    label: g_t('fleet.emergencyContactPhone'),
    required: false
  })
  // note: g_rules.commonInputText(g_t('fleet.bookingDesc'))
}

const customerKey = ref(0)
const refTravelTable = ref(null)
const refContentTable = ref(null)
const tableLoading = ref(false)
const travelColumnWidth = ref({})
const columnWidthObj = ref({})
const aiParserLoading = ref(false)
const orderTextInfo = ref('')
const addCustomerVisible = ref(false)
const addTravelVisible = ref(false)
const travelRow = ref({})
const travelType = ref('add')
const travelTableIndex = ref(0)
const selectVehicleVisible = ref(false)
const vehicleTableType = ref('')
const selectVehicleIds = ref([]) // 已选择的车辆ID
const vehicleStartTime = ref('') // 行程开始时间
const vehicleEndTime = ref('') // 行程结束时间
const vehicleTableIndex = ref(0)
const scheduleVisible = ref(false)
const detailVisible = ref(false)
const rowId = ref('')

watch(
  () => formData.value.vehicles,
  nv => {
    nextTick(() => {
      useTableColumnWidth({
        refTable: refContentTable.value
      }).getTableColumnWidth(data => {
        columnWidthObj.value = data
      })
    })
    selectVehicleIds.value = nv.map(v => v.id)
  },
  {
    // immediate: true,
    deep: true
  }
)

watch(
  () => formData.value.tripInfo,
  nv => {
    nextTick(() => {
      useTableColumnWidth({
        refTable: refTravelTable.value
      }).getTableColumnWidth(data => {
        // console.log('data', data)
        travelColumnWidth.value = data
      })
    })
  },
  {
    // immediate: true,
    deep: true
  }
)

onMounted(() => {
  if (props.row && Object.keys(props.row).length) {
    g_utils.assignFormData(formData.value, props.row)
  }
  props.type === 'edit' && getFormData()
})

const getFormData = _ => {
  formLoading.value = true
  g_api.fleet
    .apiOrderDetail({ id: props.id })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        formData.value = {
          ...formData.value,
          id: '',
          tenantId: '',
          customerId: '',
          customerName: '',
          customerContact: '',
          customerContactPhone: '',
          customerContactEmail: '',
          vehicles: [],
          customerEmergencyContact: '',
          customerEmergencyContactPhone: ''
        }
        g_utils.assignFormData(formData.value, data)
        console.log('formData.value', formData.value)
      }
    })
    .finally(() => {
      formLoading.value = false
    })
}

const handleClose = _ => {
  dialogVisible.value = false
}

const handleAddCustomer = _ => {
  addCustomerVisible.value = true
}

const handleAddTravel = _ => {
  addTravelVisible.value = true
  travelType.value = 'add'
}

const handleAddTravelCb = data => {
  formData.value.tripInfo.push(data)
}

const handleUpdateTravelCb = data => {
  console.log('data', data)
  formData.value.tripInfo.splice(travelTableIndex.value, 1, data)
}

const handleTravelEdit = (row, i) => {
  addTravelVisible.value = true
  console.log('travelRow', row)
  travelRow.value = row
  travelType.value = 'edit'
  travelTableIndex.value = i
}

const handleTravelDelete = (row, i) => {
  formData.value.tripInfo.splice(i, 1)
}

const handleAddVehicle = _ => {
  const { tripInfo } = formData.value
  selectVehicleVisible.value = true
  vehicleTableType.value = 'selection'
  vehicleStartTime.value =
    tripInfo.reduce((acc, cur) => {
      return g_dayjs(cur.startTime).isBefore(g_dayjs(acc.startTime)) ? cur : acc
    }, tripInfo[0])?.startTime || ''
  vehicleEndTime.value =
    tripInfo.reduce((acc, cur) => {
      return g_dayjs(cur.endTime).isAfter(g_dayjs(acc.endTime)) ? cur : acc
    }, tripInfo[0])?.endTime || ''
}

const handleAutoAssign = _ => {
  const startTime = formData.value.tripInfo.reduce((acc, cur) => {
    return g_dayjs(cur.startTime).isBefore(g_dayjs(acc.startTime)) ? cur : acc
  }).startTime
  const endTime = formData.value.tripInfo.reduce((acc, cur) => {
    return g_dayjs(cur.endTime).isAfter(g_dayjs(acc.endTime)) ? cur : acc
  }).endTime
  if (!startTime || !endTime) return
  tableLoading.value = true
  g_api.fleet
    .apiOrderAutoDispatch({
      // type: '1',
      orderId: props.id,
      startTime,
      endTime
    })
    .then(res => {
      if (res.code === '200') {
        ElMessage({
          message: res.message,
          type: 'success'
        })
        formData.value.vehicles = res.data
      }
    })
    .finally(() => {
      tableLoading.value = false
    })
}

const handleSelectVehicle = data => {
  if (vehicleTableType.value === 'selection') {
    formData.value.vehicles.push(...data)
  } else {
    formData.value.vehicles.splice(vehicleTableIndex.value, 1, data[0])
  }
}

const handleViewSchedule = row => {
  scheduleVisible.value = true
  rowId.value = row.id
}

const handleVehicleDetail = row => {
  detailVisible.value = true
  rowId.value = row.id
}

// const handleVehicleChange = i => {
//   selectVehicleVisible.value = true
//   vehicleTableType.value = 'radio'
//   vehicleTableIndex.value = i
// }

const handleVehicleDelete = (row, i) => {
  // g_utils
  //   .deleteConfirm(g_t('fleet.confirmDeleteVehicle'))
  //   .then(() => {
  //     formData.value.vehicles.splice(i, 1)
  //   })
  //   .catch(() => {})
  tableLoading.value = true
  g_api.fleet
    .apiVehicleUpdate({
      id: row.id,
      status: 1
    })
    .then(res => {
      if (res.code === '200') {
        ElMessage({
          message: res.message,
          type: 'success'
        })
        formData.value.vehicles.splice(i, 1)
      }
    })
    .finally(() => {
      tableLoading.value = false
    })
}

const handleInputBlur = prop => {
  // 数字化处理
  refDialogForm.value.validateField([prop], vaild => {
    if (vaild && formData.value[prop]) {
      formData.value[prop] = formData.value[prop] * 1
    }
  })
}

const handlePasteRecognize = _ => {
  aiParserLoading.value = true
  g_api.ai
    .apiAiParserText({
      type: 1,
      text: orderTextInfo.value
    })
    .then(res => {
      if (res.code === '200' && res.data) {
        ElMessage({
          message: res.message,
          type: 'success'
        })
        aiRecognAssign(res.data)
      }
    })
    .finally(() => {
      aiParserLoading.value = false
    })
}

const handleSubmitForm = () => {
  if (formLoading.value) return
  refDialogForm.value.validate(valid => {
    console.log('formData.value', formData.value)
    if (!valid) return
    formLoading.value = true
    const urlMethod =
      props.type === 'add'
        ? g_api.fleet.apiOrderCreate
        : g_api.fleet.apiOrderUpdate
    urlMethod(formData.value)
      .then(res => {
        if (res.code === '200') {
          ElMessage({
            message: res.message,
            type: 'success'
          })
          handleClose()
          emit('update')
        }
      })
      .finally(() => {
        formLoading.value = false
      })
  })
}

const aiRecognAssign = data => {
  // const data = {
  //   summary:
  //     '4月13日从广州火车站出发游览广州多个景点后送至深圳酒店；4月14日从深圳酒店送莲塘口岸进行香港一日游后入住香港酒店；4月15日从香港酒店送港珠澳大桥口岸进行澳门一日游后入住澳门酒店；4月16日从澳门酒店送人工岛进行珠海一日游。',
  //   trip: [
  //     {
  //       startCity: '广东省广州市',
  //       through: '广州海心沙亚运公园,外观小蛮腰,花城广场,海心桥,黄埔军校',
  //       startTime: '2025-04-13 00:00:00',
  //       startAddress: '广州火车站',
  //       endTime: '2025-04-13 23:59:59',
  //       endCity: '广东省深圳市',
  //       endAddress: '深圳酒店'
  //     },
  //     {
  //       startCity: '广东省深圳市',
  //       through: '莲塘口岸',
  //       startTime: '2025-04-14 00:00:00',
  //       startAddress: '深圳酒店',
  //       endTime: '2025-04-14 23:59:59',
  //       endCity: '香港',
  //       endAddress: '香港酒店'
  //     },
  //     {
  //       startCity: '香港',
  //       through: '港珠澳大桥口岸',
  //       startTime: '2025-04-15 00:00:00',
  //       startAddress: '香港酒店',
  //       endTime: '2025-04-15 23:59:59',
  //       endCity: '澳门',
  //       endAddress: '澳门酒店'
  //     },
  //     {
  //       startCity: '澳门',
  //       through: '人工岛',
  //       startTime: '2025-04-16 00:00:00',
  //       startAddress: '澳门酒店',
  //       endTime: '2025-04-16 23:59:59',
  //       endCity: '广东省珠海市',
  //       endAddress: '无'
  //     }
  //   ],
  //   count: 30,
  //   days: 4
  // }
  const mapFields = data => {
    const fieldMap = {
      count: 'peopleCount',
      days: 'days',
      summary: 'note'
    }

    Object.entries(fieldMap).forEach(([key, formKey]) => {
      formData.value[formKey] = data[key] ?? formData.value[formKey]
    })
  }
  const generateTripInfo = async data => {
    const arr = []
    for (let i = 0, len = data.trip.length; i < len; i++) {
      const item = data.trip[i]
      const startRegion = g_utils.getRegionData(item.startCity)
      const endRegion = g_utils.getRegionData(item.endCity)
      const startLnglat = await g_utils.getAMapLocation(
        startRegion.nameArr.join('') + item.startAddress
      )
      const endLnglat = await g_utils.getAMapLocation(
        endRegion.nameArr.join('') + item.endAddress
      )
      arr.push({
        startRegionCode:
          startRegion.codeArr[startRegion.codeArr.length - 1] || '',
        startAddress: item.startAddress,
        startLocation: startLnglat,
        startTime: item.startTime,
        through: item.through,
        endRegionCode: endRegion.codeArr[endRegion.codeArr.length - 1] || '',
        endAddress: item.endAddress,
        endLocation: endLnglat,
        endTime: item.endTime,
        kilometres: ''
      })
    }
    formData.value.tripInfo = arr
    console.log('formData.value.tripInfo', formData.value.tripInfo)
  }

  mapFields(data)
  generateTripInfo(data)
}
</script>

<style scoped lang="scss">
.customerWrap {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .add-customer {
    margin-left: 10px;
  }
}
.paste-identify {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  margin-top: 5px;
}
.form-item-table {
  :deep(.el-form-item__content) {
    height: 100%;
  }
  :deep(.el-scrollbar__wrap) {
    max-height: 200px;
    overflow-y: auto;
  }
}
</style>
